<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



  <meta name="google-site-verification" content="Xyy9fg5uzmq0Ysc9cQNgP4xPutZF0sBaJsjSHK55zC0" />



  <meta name="msvalidate.01" content="914C9C1CBC7078C5E2AC612AD5C1CC6C" />












  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="Solidity手册," />





  <link rel="alternate" href="/atom.xml" title="深入浅出区块链" type="application/atom+xml" />






<meta name="description" content="现在的Solidity中文文档，要么翻译的太烂，要么太旧，决定重新翻译下。尤其点名批评极客学院名为《Solidity官方文档中文版》的翻译，机器翻译的都比它好，大家还是别看了。">
<meta name="keywords" content="Solidity手册">
<meta property="og:type" content="article">
<meta property="og:title" content="智能合约语言 Solidity 教程系列1 - 类型介绍">
<meta property="og:url" content="https://learnblockchain.cn/2017/12/05/solidity1/index.html">
<meta property="og:site_name" content="深入浅出区块链">
<meta property="og:description" content="现在的Solidity中文文档，要么翻译的太烂，要么太旧，决定重新翻译下。尤其点名批评极客学院名为《Solidity官方文档中文版》的翻译，机器翻译的都比它好，大家还是别看了。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-04-12T13:05:37.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="智能合约语言 Solidity 教程系列1 - 类型介绍">
<meta name="twitter:description" content="现在的Solidity中文文档，要么翻译的太烂，要么太旧，决定重新翻译下。尤其点名批评极客学院名为《Solidity官方文档中文版》的翻译，机器翻译的都比它好，大家还是别看了。">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.3',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: 'UT2K1ZRSWK',
      apiKey: '0bbb261dfad58df8f8a657a1ed3255cd',
      indexName: 'learnblockchain',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://learnblockchain.cn/2017/12/05/solidity1/"/>





  <title>智能合约语言 Solidity 教程系列1 - 类型介绍 | 深入浅出区块链</title>
  








  <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<script>
    (adsbygoogle = window.adsbygoogle || []).push({
        google_ad_client: "ca-pub-6273382609469378",
        enable_page_level_ads: true
    });
</script>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">深入浅出区块链</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">系统学习区块链技术</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-wiki">
          <a href="https://wiki.learnblockchain.cn" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-book"></i> <br />
            
            Wiki
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  
  <div class="algolia-popup popup search-popup">
    <div class="algolia-search">
      <div class="algolia-search-input-icon">
        <i class="fa fa-search"></i>
      </div>
      <div class="algolia-search-input" id="algolia-search-input"></div>
    </div>

    <div class="algolia-results">
      <div id="algolia-stats"></div>
      <div id="algolia-hits"></div>
      <div id="algolia-pagination" class="algolia-pagination"></div>
    </div>

    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
  </div>




    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://learnblockchain.cn/2017/12/05/solidity1/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Tiny熊">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="深入浅出区块链">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">智能合约语言 Solidity 教程系列1 - 类型介绍</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-12-05T15:25:59+08:00">
                2017-12-05
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">更新于&#58;</span>
              
              <time title="更新于" itemprop="dateModified" datetime="2018-04-12T21:05:37+08:00">
                2018-04-12
              </time>
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/ethereum/" itemprop="url" rel="index">
                    <span itemprop="name">以太坊</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/ethereum/Solidity/" itemprop="url" rel="index">
                    <span itemprop="name">Solidity</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>现在的Solidity中文文档，要么翻译的太烂，要么太旧，决定重新翻译下。<br>尤其点名批评极客学院名为《Solidity官方文档中文版》的翻译，机器翻译的都比它好，大家还是别看了。</p>
<a id="more"></a>
<h2 id="写在前面"><a href="#写在前面" class="headerlink" title="写在前面"></a>写在前面</h2><p>Solidity是以太坊智能合约编程语言，阅读本文前，你应该对以太坊、智能合约有所了解，<br>如果你还不了解，建议你先看<a href="https://learnblockchain.cn/2017/11/20/whatiseth/">以太坊是什么</a><br>Solidity教程会是一系列文章，本文是第一篇：介绍Solidity的变量类型。<br>Solidity 系列完整的文章列表请查看<a href="https://learnblockchain.cn/categories/ethereum/Solidity/">分类-Solidity</a>。</p>
<p>本文前半部分是参考Solidity官方文档（当前最新版本：0.4.20）进行翻译，后半部分是结合实际合约代码实例说明类型的使用（仅针对<a href="https://xiaozhuanlan.com/blockchaincore" target="_blank" rel="noopener">专栏</a>订阅用户）。</p>
<h2 id="类型"><a href="#类型" class="headerlink" title="类型"></a>类型</h2><p>Solidity是一种静态类型语言，意味着每个变量（本地或状态变量）需要在编译时指定变量的类型（或至少可以推倒出类型）。Solidity提供了一些基本类型可以用来组合成复杂类型。</p>
<p>Solidity类型分为两类：</p>
<ul>
<li>值类型(Value Type) - 变量在赋值或传参时，总是进行值拷贝。</li>
<li>引用类型(Reference Types)</li>
</ul>
<h3 id="值类型-Value-Type"><a href="#值类型-Value-Type" class="headerlink" title="值类型(Value Type)"></a>值类型(Value Type)</h3><p><strong>值类型</strong>包含:</p>
<ul>
<li>布尔类型(Booleans)</li>
<li>整型(Integers)</li>
<li>定长浮点型(Fixed Point Numbers)</li>
<li>定长字节数组(Fixed-size byte arrays)</li>
<li>有理数和整型常量(Rational and Integer Literals)</li>
<li>字符串常量（String literals）</li>
<li>十六进制常量（Hexadecimal literals）</li>
<li>枚举(Enums)</li>
<li><a href="https://learnblockchain.cn/2017/12/12/solidity_func/">函数类型</a>(Function Types)</li>
<li><a href="https://learnblockchain.cn/2017/12/12/solidity2/">地址类型</a>(Address)</li>
<li>地址常量(Address Literals)<blockquote>
<p><a href="https://learnblockchain.cn/2017/12/12/solidity_func/">函数类型</a>及<a href="https://learnblockchain.cn/2017/12/12/solidity2/">地址类型</a>(Address)有单独的博文，请点击查看。</p>
</blockquote>
</li>
</ul>
<h2 id="布尔类型-Booleans"><a href="#布尔类型-Booleans" class="headerlink" title="布尔类型(Booleans)"></a>布尔类型(Booleans)</h2><p><strong>布尔(bool)</strong>:可能的取值为常量值<strong>true</strong>和<strong>false</strong>。</p>
<p>布尔类型支持的运算符有：</p>
<ul>
<li>！逻辑非</li>
<li>&amp;&amp; 逻辑与</li>
<li>|| 逻辑或</li>
<li>== 等于</li>
<li>!= 不等于</li>
</ul>
<p>注意：运算符<strong>&amp;&amp;</strong>和<strong>||</strong>是短路运算符，如f(x)||g(y)，当f(x)为真时，则不会继续执行g(y)。</p>
<h2 id="整型-Integers"><a href="#整型-Integers" class="headerlink" title="整型(Integers)"></a>整型(Integers)</h2><p><strong>int</strong>/<strong>uint</strong>: 表示有符号和无符号不同位数整数。支持关键字<strong>uint8</strong> 到 <strong>uint256</strong> (以8步进)，<br><strong>uint</strong> 和 <strong>int</strong> 默认对应的是 <strong>uint256</strong> 和 <strong>int256</strong>。</p>
<p>支持的运算符：</p>
<ul>
<li>比较运算符： &lt;=, &lt; , ==, !=, &gt;=, &gt; (返回布尔值：true 或 false)</li>
<li>位操作符： &amp;，|，^(异或)，~（位取反）</li>
<li>算术操作符：+，-，一元运算-，一元运算+，<em>，/, %(取余数), **</em>（幂）, &lt;&lt; (左移位), &gt;&gt;(右移位)</li>
</ul>
<p>说明：</p>
<ol>
<li>整数除法总是截断的，但如果运算符是字面量（字面量稍后讲)，则不会截断。</li>
<li>整数除0会抛异常。</li>
<li>移位运算的结果的正负取决于操作符左边的数。x &lt;&lt; y 和 x <em> 2**</em>y 是相等， x &gt;&gt; y 和 x / 2**y 是相等的。</li>
<li>不能进行负移位，即操作符右边的数不可以为负数，否则会抛出运行时异常。</li>
</ol>
<p>注意：Solidity中，右移位是和除等价的，因此右移位一个负数，向下取整时会为0，而不像其他语言里为无限负小数。</p>
<h2 id="定长浮点型（Fixed-Point-Numbers）"><a href="#定长浮点型（Fixed-Point-Numbers）" class="headerlink" title="定长浮点型（Fixed Point Numbers）"></a>定长浮点型（Fixed Point Numbers）</h2><p>注意：定长浮点型 Solidity（发文时）还不完全支持，它可以用来声明变量，但不可以用来赋值。</p>
<p><strong>fixed</strong>/<strong>ufixed</strong>: 表示有符号和无符号的固定位浮点数。关键字为<strong>ufixedMxN</strong> 和 <strong>ufixedMxN</strong>。<br><strong>M</strong>表示这个类型要占用的位数，以8步进，可为8到256位。<br><strong>N</strong>表示小数点的个数，可为0到80之间</p>
<p>支持的运算符：</p>
<ul>
<li>比较运算符： &lt;=, &lt; , ==, !=, &gt;=, &gt; (返回布尔值：true 或 false)</li>
<li>算术操作符：+，-，一元运算-，一元运算+，<em>，/, %(取余数)<br>注意：它和大多数语言的float和double不一样，<em>*M</em></em>是表示整个数占用的固定位数，包含整数部分和小数部分。因此用一个小位数（M较小）来表示一个浮点数时，小数部分会几乎占用整个空间。</li>
</ul>
<h2 id="定长字节数组-Fixed-size-byte-arrays"><a href="#定长字节数组-Fixed-size-byte-arrays" class="headerlink" title="定长字节数组(Fixed-size byte arrays)"></a>定长字节数组(Fixed-size byte arrays)</h2><p>关键字有：bytes1, bytes2, bytes3, …, bytes32。（以步长1递增）<br>byte代表bytes1。</p>
<p>支持的运算符：</p>
<ul>
<li>比较符: &lt;=, &lt;, ==, !=, &gt;=, &gt; (返回bool）</li>
<li>位操作符: &amp;, |, ^ (按位异或)，~（按位取反）, &lt;&lt; (左移位), &gt;&gt; (右移位)</li>
<li>索引（下标）访问: 如果x是bytesI，当0 &lt;= k &lt; I ，则x[k]返回第k个字节（只读）。</li>
</ul>
<p>移位运算和整数类似，移位运算的结果的正负取决于操作符左边的数，且不能进行负移位。<br>如可以-5&lt;&lt;1, 不可以5&lt;&lt;-1</p>
<p>成员变量：<br><strong>.length</strong>：表示这个字节数组的长度（只读）。</p>
<h2 id="变长（动态分配大小）字节数组（Dynamically-sized-byte-array）"><a href="#变长（动态分配大小）字节数组（Dynamically-sized-byte-array）" class="headerlink" title="变长（动态分配大小）字节数组（Dynamically-sized byte array）"></a>变长（动态分配大小）字节数组（Dynamically-sized byte array）</h2><ul>
<li>bytes:动态分配大小字节数组, 参见<a href="http://solidity.readthedocs.io/en/latest/types.html#arrays" target="_blank" rel="noopener">Arrays</a>,不是值类型!</li>
<li>string:动态分配大小UTF8编码的字符类型,参看<a href="http://solidity.readthedocs.io/en/latest/types.html#arrays" target="_blank" rel="noopener">Arrays</a>。不是值类型!</li>
</ul>
<p>根据经验：<br>bytes用来存储任意长度的字节数据，string用来存储任意长度的(UTF-8编码)的字符串数据。<br>如果长度可以确定，尽量使用定长的如byte1到byte32中的一个，因为这样更省空间。</p>
<h2 id="有理数和整型常量-Rational-and-Integer-Literals"><a href="#有理数和整型常量-Rational-and-Integer-Literals" class="headerlink" title="有理数和整型常量(Rational and Integer Literals)"></a>有理数和整型常量(Rational and Integer Literals)</h2><blockquote>
<p>也有人把Literals翻译为字面量</p>
</blockquote>
<p>整型常量是有一系列0-9的数字组成，10进制表示，比如：8进制是不存在的，前置0在Solidity中是无效的。</p>
<p>10进制小数常量（Decimal fraction literals）带了一个<strong>.</strong>， 在<strong>.</strong>的两边至少有一个数字，有效的表示如:<strong>1.</strong>, <strong>.1</strong> 和 <strong>1.3</strong>.</p>
<p>科学符号也支持，基数可以是小数，指数必须是整数， 有效的表示如: <strong>2e10</strong>, <strong>-2e10</strong>, <strong>2e-10</strong>, <strong>2.5e1</strong>。</p>
<p>数字常量表达式本身支持任意精度，也就是可以不会运算溢出，或除法截断。但当它被转换成对应的非常量类型，或者将他们与非常量进行运算，则不能保证精度了。<br>如：(2*<strong>800 + 1) - 2*</strong>800的结果为1（uint8整类) ，尽管中间结果已经超过计算机字长。另外：<strong>.5 * 8</strong>的结果是4，尽管有非整形参与了运算。</p>
<p>只要操作数是整形，整型支持的运算符都适用于整型常量表达式。<br>如果两个操作数是小数，则不允许进行位运算，指数也不能是小数。</p>
<p>注意：<br>Solidity对每一个有理数都有一个数值常量类型。整数常量和有理数常量从属于数字常量。所有的数字常表达式的结果都属于数字常量。所以1 + 2和2 + 1都属于同样的有理数的数字常量3</p>
<p>警告：<br>整数常量除法，在早期的版本中是被截断的，但现在可以被转为有理数了，如5/2的值为 2.5</p>
<p>注意：<br>数字常量表达式，一旦其中含有常量表达式，它就会被转为一个非常量类型。下面代码中表达式的结果将会被认为是一个有理数：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">uint128 a = 1;</span><br><span class="line">uint128 b = 2.5 + a + 0.5;</span><br></pre></td></tr></table></figure></p>
<p>上述代码编译不能通过，因为b会被编译器认为是小数型。</p>
<h2 id="字符串常量"><a href="#字符串常量" class="headerlink" title="字符串常量"></a>字符串常量</h2><p>字符串常量是指由单引号，或双引号引起来的字符串 (“foo” or ‘bar’)。字符串并不像C语言，包含结束符，”foo”这个字符串大小仅为三个字节。和整数常量一样，字符串的长度类型可以是变长的。字符串可以隐式的转换为byte1,…byte32 如果适合，也会转为bytes或string。</p>
<p>字符串常量支持转义字符，比如\n，\xNN，\uNNNN。其中\xNN表示16进制值，最终转换合适的字节。而\uNNNN表示Unicode编码值，最终会转换为UTF8的序列。</p>
<h2 id="十六进制常量（Hexadecimal-literals）"><a href="#十六进制常量（Hexadecimal-literals）" class="headerlink" title="十六进制常量（Hexadecimal literals）"></a>十六进制常量（Hexadecimal literals）</h2><p>十六进制常量，以关键字hex打头，后面紧跟用单或双引号包裹的字符串，内容是十六进制字符串，如hex”001122ff”。<br>它的值会用二进制来表示。</p>
<p>十六进制常量和字符串常量类似，也可以转换为字节数组。</p>
<h2 id="枚举（Enums）"><a href="#枚举（Enums）" class="headerlink" title="枚举（Enums）"></a>枚举（Enums）</h2><p>在Solidity中，枚举可以用来自定义类型。它可以显示的转换与整数进行转换，但不能进行隐式转换。显示的转换会在运行时检查数值范围，如果不匹配，将会引起异常。枚举类型应至少有一名成员。下面是一个枚举的例子：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">pragma solidity ^0.4.0;</span><br><span class="line"></span><br><span class="line">contract test &#123;</span><br><span class="line">    enum ActionChoices &#123; GoLeft, GoRight, GoStraight, SitStill &#125;</span><br><span class="line">    ActionChoices choice;</span><br><span class="line">    ActionChoices constant defaultChoice = ActionChoices.GoStraight;</span><br><span class="line"></span><br><span class="line">    function setGoStraight() &#123;</span><br><span class="line">        choice = ActionChoices.GoStraight;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    // Since enum types are not part of the ABI, the signature of &quot;getChoice&quot;</span><br><span class="line">    // will automatically be changed to &quot;getChoice() returns (uint8)&quot;</span><br><span class="line">    // for all matters external to Solidity. The integer type used is just</span><br><span class="line">    // large enough to hold all enum values, i.e. if you have more values,</span><br><span class="line">    // `uint16` will be used and so on.</span><br><span class="line">    function getChoice() returns (ActionChoices) &#123;</span><br><span class="line">        return choice;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    function getDefaultChoice() returns (uint) &#123;</span><br><span class="line">        return uint(defaultChoice);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="代码实例"><a href="#代码实例" class="headerlink" title="代码实例"></a>代码实例</h2><p>通过合约代码实例说明类型的使用，请订阅<a href="https://xiaozhuanlan.com/blockchaincore" target="_blank" rel="noopener">区块链技术</a>查看。</p>
<h2 id="参考文档"><a href="#参考文档" class="headerlink" title="参考文档"></a>参考文档</h2><p><a href="https://solidity.readthedocs.io/en/develop/types.html" target="_blank" rel="noopener">Solidity官方文档-类型</a></p>
<p><a href="https://learnblockchain.cn/">深入浅出区块链</a> - 系统学习区块链，打造最好的区块链技术博客。<br>我的<strong><a href="https://t.xiaomiquan.com/RfAu7uj" target="_blank" rel="noopener">知识星球</a></strong>为各位解答区块链技术问题，欢迎加入讨论。</p>
<!---
下面我们用一个真实的合约代码来理解下各个类型及操作符。
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">pragma solidity ^<span class="number">0.4</span><span class="number">.18</span>;</span><br><span class="line"></span><br><span class="line">contract testType&#123;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">add</span>(<span class="params">uint x, uint y</span>) <span class="title">public</span> <span class="title">returns</span> (<span class="params">uint z</span>)</span>&#123;</span><br><span class="line">        z = x + y;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">divide</span>(<span class="params">uint x, uint y </span>) <span class="title">public</span> <span class="title">returns</span> (<span class="params">uint z</span>) </span>&#123;</span><br><span class="line">        z = x / y;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">leftshift</span>(<span class="params">int x, uint y</span>) <span class="title">public</span> <span class="title">returns</span> (<span class="params">int z</span>)</span>&#123;</span><br><span class="line">        z = x &lt;&lt; y;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">rightshift</span>(<span class="params">int x, uint y</span>) <span class="title">public</span> <span class="title">returns</span> (<span class="params">int z</span>)</span>&#123;</span><br><span class="line">        z = x &gt;&gt; y;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">interLiteral</span>(<span class="params"></span>) <span class="title">public</span> <span class="title">returns</span> (<span class="params">uint, uint</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> ((<span class="number">2</span>**<span class="number">800</span> + <span class="number">1</span>) - <span class="number">2</span>**<span class="number">800</span>,  <span class="number">0.5</span>*<span class="number">8</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">hexLiteralBytes</span>(<span class="params"></span>) <span class="title">public</span> <span class="title">returns</span> (<span class="params">bytes2, bytes1, bytes1</span>) </span>&#123;</span><br><span class="line">        bytes2 a = hex<span class="string">"aabb"</span>;</span><br><span class="line">        <span class="keyword">return</span> (a, a[<span class="number">0</span>], a[<span class="number">1</span>]);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="运行"><a href="#运行" class="headerlink" title="运行"></a>运行</h3><ol>
<li>打开<a href="https://ethereum.github.io/browser-solidity">browser-solidity</a>，把代码拷贝到编辑器。</li>
<li>选择环境创建合约</li>
<li>传参数调用</li>
<li>点Details 查看结果<br>上一张截图大家就明白了。<br><img src="(https://diycode.b0.upaiyun.com/photo/2017/b2b5529012ae930f5ae3e9a700247cbe.jpg" alt=""></li>
</ol>
<p>建议根据自己对类型的理解，修改代码，使用不同的参数进行调用以增强对类型的理解。<br>如：运行hexLiteralBytes()查看输出结果，十六进制常量可转化为字节数组。<br><img src="https://diycode.b0.upaiyun.com/photo/2017/e28c82c8442eca12422d32b9d6563dfa.jpg" alt=""></p>
<p>–&gt;</p>
-->
      
    </div>
    
    
    

    
      <div>
        <div id="wechat_subscriber" style="display: block; padding: 10px 0; margin: 20px auto; width: 100%; text-align: center">
    <img id="wechat_subscriber_qcode" src="/images/qrcode.jpg" alt="Tiny熊 wechat" style="width: 200px; max-width: 100%;"/>
    <div>微信号：深入浅出区块链技术，欢迎订阅</div>
</div>

      </div>
    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>有收获，赞赏下</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/qr_pay.jpg" alt="Tiny熊 微信支付"/>
        <p>微信支付</p>
      </div>
    

    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    Tiny熊
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://learnblockchain.cn/2017/12/05/solidity1/" title="智能合约语言 Solidity 教程系列1 - 类型介绍">https://learnblockchain.cn/2017/12/05/solidity1/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本文采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/deed.zh" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Solidity手册/" rel="tag"># Solidity手册</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/12/01/geth_cmd_short/" rel="next" title="Geth 控制台使用及 Web3.js 使用实战">
                <i class="fa fa-chevron-left"></i> Geth 控制台使用及 Web3.js 使用实战
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/12/07/bitcoin-sonsensus/" rel="prev" title="比特币如何达成共识 - 最长链的选择">
                比特币如何达成共识 - 最长链的选择 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">Tiny熊</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">40</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">12</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">51</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          <div class="links-of-author motion-element">
            
              
                <span class="links-of-author-item">
                  <a href="https://github.com/xilibi2003" target="_blank" title="GitHub">
                    
                      <i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="http://weibo.com/xilibi2003" target="_blank" title="Weibo">
                    
                      <i class="fa fa-fw fa-weibo"></i>Weibo</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.zhihu.com/people/xiong-li-bing/activities" target="_blank" title="ZhiHu">
                    
                      <i class="fa fa-fw fa-globe"></i>ZhiHu</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:xilibi2003@gmail.com" target="_blank" title="E-Mail">
                    
                      <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                </span>
              
            
          </div>

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                友链
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://xiaozhuanlan.com/blockchaincore" title="区块链技术专栏" target="_blank">区块链技术专栏</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://t.xiaomiquan.com/RfAu7uj" title="技术交流-知识星球" target="_blank">技术交流-知识星球</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://bitshuo.com" title="区块链技术中文社区" target="_blank">区块链技术中文社区</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://news.tangwen.org" title="汤问资讯" target="_blank">汤问资讯</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.bitask.org" title="币问" target="_blank">币问</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.hubwiz.com/course?affid＝lbc" title="汇智网互动课程中心" target="_blank">汇智网互动课程中心</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://hiblock.net/" title="HiBlock区块链社区" target="_blank">HiBlock区块链社区</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://eosfans.io/" title="EOS中文社区" target="_blank">EOS中文社区</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://blockflow.net/" title="BlockFlow" target="_blank">BlockFlow</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#写在前面"><span class="nav-number">1.</span> <span class="nav-text">写在前面</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#类型"><span class="nav-number">2.</span> <span class="nav-text">类型</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#值类型-Value-Type"><span class="nav-number">2.1.</span> <span class="nav-text">值类型(Value Type)</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#布尔类型-Booleans"><span class="nav-number">3.</span> <span class="nav-text">布尔类型(Booleans)</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#整型-Integers"><span class="nav-number">4.</span> <span class="nav-text">整型(Integers)</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#定长浮点型（Fixed-Point-Numbers）"><span class="nav-number">5.</span> <span class="nav-text">定长浮点型（Fixed Point Numbers）</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#定长字节数组-Fixed-size-byte-arrays"><span class="nav-number">6.</span> <span class="nav-text">定长字节数组(Fixed-size byte arrays)</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#变长（动态分配大小）字节数组（Dynamically-sized-byte-array）"><span class="nav-number">7.</span> <span class="nav-text">变长（动态分配大小）字节数组（Dynamically-sized byte array）</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#有理数和整型常量-Rational-and-Integer-Literals"><span class="nav-number">8.</span> <span class="nav-text">有理数和整型常量(Rational and Integer Literals)</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#字符串常量"><span class="nav-number">9.</span> <span class="nav-text">字符串常量</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#十六进制常量（Hexadecimal-literals）"><span class="nav-number">10.</span> <span class="nav-text">十六进制常量（Hexadecimal literals）</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#枚举（Enums）"><span class="nav-number">11.</span> <span class="nav-text">枚举（Enums）</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#代码实例"><span class="nav-number">12.</span> <span class="nav-text">代码实例</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#参考文档"><span class="nav-number">13.</span> <span class="nav-text">参考文档</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Tiny熊</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a></div>



  <div class="footer-custom"><a target="_blank" href="http://www.miitbeian.gov.cn/">粤ICP备17140514号-1</a></div>


        







  <div style="display: none;">
    <script src="//s95.cnzz.com/z_stat.php?id=1265946080&web_id=1265946080" language="JavaScript"></script>
  </div>



        
      </div>
    </footer>

    

    
      <div id="needsharebutton-float">
        <span class="btn">
          <i class="fa fa-share-alt" aria-hidden="true"></i>
        </span>
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.3"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>



  


  




	





  





  












  




  
  
  
  <link rel="stylesheet" href="/lib/algolia-instant-search/instantsearch.min.css">

  
  
  <script src="/lib/algolia-instant-search/instantsearch.min.js"></script>
  

  <script src="/js/src/algolia-search.js?v=5.1.3"></script>



  

  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">

  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
    
      flOptions = {};
      
          flOptions.iconStyle = "default";
      
          flOptions.boxForm = "horizontal";
      
          flOptions.position = "middleRight";
      
          flOptions.networks = "Weibo,Wechat,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-float', flOptions);
    
  </script>

  

  

  

  

</body>
</html>
